const userModel = require("../models/userModel");
const formatMessage = require("../utils/formatMessage");

// 注册
const register = async (ctx, next) => {
  const username = ctx.request.body.username;
  const isRegistered = await userModel.getUsers({ username });
  if (isRegistered && isRegistered.length) {
    ctx.body = formatMessage(500, "用户名已注册");
  } else {
    const res = await userModel.register(ctx.request.body);
    if (res instanceof Error) {
      ctx.body = formatMessage(500, res);
    } else {
      ctx.body = formatMessage(200, "注册成功");
    }
  }
};
// 登入
const login = async (req, res) => {
  let { username, password } = req.body;
  let query = { username };
  const result = await findUser(query);
  if (result.length) {
    //用户存在时校验密码
    let hashPassword = result[0].password;
    let id = result[0]["id"];
    if (verify) {
      let userInfo = {
        username: result[0]["username"],
        nickname: result[0]["nickname"],
      };
      //将用户信息挂载到当前请求的session上面
      // req.session.userInfo = userInfo;
      res.send({ httpStatus: 200, msg: "登入成功", id, username });
      // res.send({ httpStatus: 200, msg: "登入成功", id: "1", username });
    } else {
      res.send({ httpStatus: 400, msg: "密码错误" });
    }
  } else {
    res.send({ httpStatus: 400, msg: "用户不存在" });
  }
};
//获取用户
const getUsers = async (ctx, next) => {
  const res = await userModel.getUsers(req.query);
  if (res.length) {
  } else {
  }
};
//修改用户密码
const updatePassword = async (req, res) => {
  //用旧密码更新新密码
  let { username, oldPassword, newPassword } = req.body;
  let isUnique = await findUser({ username });
  if (isUnique.length) {
    //表存在该用户
    let hashPassword = isUnique[0].password;
    if (verify) {
      //密码比对成功
      let salt = 10;

      //声明更新条件
      let query = { username };
      let updated = { $set: { password: newHashPassword } };
      let updateResult = await updateUserInfo(query, updated);
      if (updateResult.n) {
        res.send({ httpStatus: 200, msg: "密码修改成功" });
      } else {
        res.send({ httpStatus: 400, msg: "密码修改出错" });
      }
    } else {
      res.send({ httpStatus: 400, msg: "旧密码有误" });
    }
  } else {
    res.send({ httpStatus: 400, msg: "该用户不存在" });
  }
};

const uploadAvatar = async (req, res, next) => {
  const { id } = req.body;
  let updated = { $set: { avatar: req.body.avatarUrl } };
  let result = await updateUserInfo({ id }, updated);
  if (result.n) {
    res.send({ httpStatus: 200, msg: "图片上传成功" });
    next();
  } else {
    res.send({ httpStatus: 400, msg: "图片上传失败" });
    // next();
  }
  next();
};
//退出
const quit = (req, res) => {
  req.session.destroy();
  res.send({ httpStatus: 200, msg: "退出登入" });
};
module.exports = {
  register,
};
